package com.fang.transfer.file.common;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Service
public class ChannelManagement {

    Map<String, ChannelHandlerContext> channelById = new ConcurrentHashMap<String, ChannelHandlerContext>();

    public void add(String id, ChannelHandlerContext ctx) {
        channelById.put(id, ctx);
        log.info("设备连接成功,设备id:{}", id);
    }


    public ChannelHandlerContext get(String id) {
        return channelById.get(id);
    }


    public void remove(ChannelHandlerContext ctx) {
        ChannelId channelId = ctx.channel().id();
        String id = channelId.toString();
        if (StringUtils.isEmpty(id)) {
            log.info("设备不存在,channelId:{}", channelId.toString());
            return;
        }
        ChannelHandlerContext context = channelById.remove(id);
        if (context == null) {
            log.info("管道不存在,id:{}", id);
            return;
        }
    }

}
